package com.founder.gateway.oauth.cover;

import com.founder.gateway.system.bean.SetuSession;
import com.founder.gateway.system.util.BeanUtil;
import org.springframework.security.oauth2.provider.AuthorizationRequest;
import org.springframework.security.web.WebAttributes;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;

@Controller
public class OAuthController {
    @RequestMapping("/oauth/confirm_access")
    public ModelAndView getAccessConfirmation(@SessionAttribute("authorizationRequest") AuthorizationRequest authorizationRequest, Principal principal) {
        Map<String, Object> model = new HashMap<>();
        String name = principal.getName();
        SetuSession sessionBean = BeanUtil.getSession();
        if (sessionBean != null) {
            String nickname = sessionBean.getUserName();
            if (StringUtils.hasText(nickname)) {
                name = nickname + "(" + name + ")";
            }
        }
        model.put("name", name);
        model.put("clientId", authorizationRequest.getClientId());
        return new ModelAndView("cover/approval", model);
    }

    @RequestMapping("/login")
    public ModelAndView login(HttpServletRequest request) {
        Map<String, Object> model = new HashMap<>();
        if (request.getParameter("error") != null) {
            HttpSession session = request.getSession(false);
            if (session != null) {
                Exception exception = (Exception) session.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
                model.put("error", exception != null ? exception.getMessage() : "Invalid credentials");
            }
        }
        return new ModelAndView("cover/login", model);
    }
}
